package com.harvest.scientific.ladder.page

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.ViewGroup
import android.widget.Button
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.harvest.scientific.ladder.R
import com.harvest.scientific.ladder.base.BaNoActivity
import com.harvest.scientific.ladder.base.IFragment
import com.harvest.scientific.ladder.constant.PageArgs
import com.harvest.scientific.ladder.databinding.ActivityHomeBinding
import com.harvest.scientific.ladder.ext.invisible
import com.harvest.scientific.ladder.ext.visible
import com.harvest.scientific.ladder.page.fa.AuditingFragment
import com.harvest.scientific.ladder.page.fa.HomeFragment
import com.harvest.scientific.ladder.page.fa.MineFragment
import com.harvest.scientific.ladder.page.fa.MultiFragment
import com.harvest.scientific.ladder.page.fa.OrderFragment
import com.harvest.scientific.ladder.page.fa.RefusedFragment
import com.harvest.scientific.ladder.page.ui.main.HomeIntent
import com.harvest.scientific.ladder.page.ui.main.InjurePacificChickenRes
import com.harvest.scientific.ladder.page.ui.main.LoadUiState
import com.harvest.scientific.ladder.page.ui.main.MainViewModel
import com.harvest.scientific.ladder.util.FlowBus
import com.harvest.scientific.ladder.util.FlowBusConstant
import com.harvest.scientific.ladder.util.LogUtils
import com.harvest.scientific.ladder.util.isLogin
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class HomeActivity : BaNoActivity<ActivityHomeBinding>() {

    private var injures: Array<InjurePacificChickenRes>? = null
    private var selectedIndex: Int = 0
    private var fromType: Int = 0
    private val viewModel: MainViewModel by viewModels()
    private val fragments = arrayListOf<Fragment>(
//        HomeFragment.newInstance(),
//        OrderFragment.newInstance(),
//        MineFragment.newInstance()
    )

    override fun initPage(savedInstanceState: Bundle?) {
        initArgs(savedInstanceState)
        _binding.refreshView.setProgressViewOffset(true, 0, 200)
        initBottom()
        initAdapter()
        initListener()
//        AmountSelectActivity.jump(this)
//        startActivity(Intent(this, Info2Activity::class.java))

        loadData()
        FlowBus.with<Unit>(FlowBusConstant.GO_HOME).register(this) {
            selectedIndex = 0
            switchBottom()
            selectPage(selectedIndex)
        }

    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        LogUtils.d("HomeActivity onnewIntent")
        loadData()
    }

    private fun loadData() {
        if (injures != null && !injures.isNullOrEmpty()) {
            injures?.takeIf { it.isNotEmpty() }?.let { res ->

                LogUtils.d("injures size :${res.size}")
                if (res.size == 1) {
                    showLoading()
                    viewModel.dislikeRoughSpear()
                } else {
                    fragments.add(MultiFragment.newInstance())
                    fragments.add(MineFragment.newInstance())
                    _binding.viewPager.adapter?.notifyDataSetChanged()
                }
                injures = null
            }
        } else {
            showLoading()
            viewModel.sendUiIntent(HomeIntent.QueryInjurePacificChicken)
        }
    }

    override fun onResume() {
        super.onResume()
    }

    private fun initListener() {
        _binding.refreshView.setOnRefreshListener {
            loadData()
        }
        FlowBus.with<Unit>(FlowBusConstant.REFRESH_HOME).register(this) {
            loadData()
        }
        lifecycleScope.launch {
            launch {
                viewModel.uiStateFlow.collectLatest { res ->
                    LogUtils.d("uiStateFlow $res")
                    when (res) {
                        is LoadUiState.QueryInjurePacificChicken -> {
                            LogUtils.i("QueryInjurePacificChicken, data:${res.datas}")
                            fragments.clear()
                            if (res.datas.size > 1) {
                                // multi
//                                fragments[0] = MultiFragment.newInstance()
//                                _binding.viewPager.adapter?.notifyItemChanged(0)
                                fragments.add(0, MultiFragment.newInstance())
                            } else {
                                fragments.add(0, HomeFragment.newInstance())
                            }
                            fragments.add(MineFragment.newInstance())

                            _binding.viewPager.adapter?.notifyDataSetChanged()
                            _binding.viewPager.post {
                                val isShowOrder = fragments.any { it is OrderFragment }
                                if (isShowOrder) {
                                    _binding.orderBarContainer.visible()
                                }
                                switchBottom()
                            }
                        }

                        is LoadUiState.DislikeRoughSpear -> {

                            LogUtils.d("DislikeRoughSpear res->$res")
                            val oStatus = res.data.magicNeckCourtConceitedLaughter
                            val loanStatus = res.data.bothPondUnimportantChimneyGuide
                            LogUtils.d("LoseGrandComfortResState res, oStatus->$oStatus, loanStatus:$loanStatus")
//                            fragments.clear()
                            val tempList = arrayListOf<Fragment>()

                            when (oStatus) {
                                0 -> {
                                    // huankuan
                                }
                                1 -> {
                                    // yuqi

                                }
                                3 -> {
                                    // refused
//                                    if (fragments[0] !is RefusedFragment) {
//                                        fragments[0] = RefusedFragment.newInstance()
//                                        _binding.viewPager.adapter?.notifyItemChanged(0)
//                                    }
                                    tempList.add(0, RefusedFragment.newInstance())
                                }
                                2 -> when (loanStatus) {
                                    2 -> {
                                        //fail
                                    }
                                    3 -> {
                                        //fangkuan ing
                                    }
                                    else -> {
                                        //auditing ing
//                                        if (fragments[0] !is AuditingFragment) {
//                                            fragments[0] = AuditingFragment.newInstance()
//                                            _binding.viewPager.adapter?.notifyItemChanged(0)
//                                        }
                                        tempList.add(0, AuditingFragment.newInstance())
//                                        fragments[0] = AuditingFragment.newInstance()
                                    }
                                }

                                else -> {
                                    // default
                                    // single
                                    tempList.add(0, HomeFragment.newInstance())
//                                    if (fragments[0] !is HomeFragment) {
//                                        fragments[0] = HomeFragment.newInstance()
//                                        _binding.viewPager.adapter?.notifyItemChanged(0)
//
//                                    } else {
//                                        LogUtils.d("already is homefragment")
//                                    }
                                }
                            }
                            if (tempList.size == 0) {
                                tempList.add(0, HomeFragment.newInstance())
                            }
                            tempList.add(MineFragment.newInstance())

                            if (fragments.isEmpty()) {
                                LogUtils.d("add fragment 111")
                                fragments.addAll(tempList)
                                _binding.viewPager.adapter?.notifyDataSetChanged()
                            } else {
                                if (fragments.size != tempList.size) {
                                    LogUtils.d("add fragment 222")
                                    fragments.clear()
                                    fragments.addAll(tempList)
                                    _binding.viewPager.adapter?.notifyDataSetChanged()
                                } else {
                                    var flag = false
                                    for ((index, fr) in tempList.withIndex()) {
                                        if (fr::class != fragments[index]::class) {
                                            flag = true
                                            break
                                        }
                                    }
                                    LogUtils.d("add fragment 333 flag:$flag")
                                    if (flag) {
                                        fragments.clear()
                                        fragments.addAll(tempList)
                                        _binding.viewPager.adapter?.notifyDataSetChanged()
                                    } else {
                                        (fragments[selectedIndex] as? IFragment)?.loadData()
                                    }
                                }
                            }


                            val isShowOrder = fragments.any { it is OrderFragment }
                            if (isShowOrder) {
                                _binding.orderBarContainer.visible()
                            }
                            switchBottom()

                        }


                        else -> {

                        }
                    }
                    LogUtils.d("dismissLoading :${res}")
                    _binding.root.postDelayed({
                        dismissLoading()
                        _binding.refreshView.isRefreshing = false
                        _binding.viewPager.post {
                            var index = 0
                            if (fromType == PageArgs.FROM_MINE) {
                                index = if (_binding.orderBarContainer.isVisible) 2 else 1
                            }
                            LogUtils.d("jump index :$index")
                            _binding.viewPager.setCurrentItem(index, false)
                        }
                    }, 700)

                }
            }
        }
    }


    private fun initBottom() {
        _binding.bottomBarContainer.apply {
            switchBottom()
            _binding.homeBarContainer.setOnClickListener {
                selectedIndex = 0
                switchBottom()
                selectPage(selectedIndex)
            }
            _binding.orderBarContainer.setOnClickListener {
                selectedIndex = 1
                switchBottom()
                selectPage(selectedIndex)
            }
            _binding.mineBarContainer.setOnClickListener {
                if (!isLogin()) {
                    LoginActivity.jump(this@HomeActivity, PageArgs.FROM_MINE)
                    return@setOnClickListener
                }
                selectedIndex = if (_binding.orderBarContainer.isVisible) 2 else 1
                switchBottom()
                selectPage(selectedIndex)
            }

        }

    }

    private fun switchBottom() {

        _binding.homeIcon.setImageResource(R.mipmap.home_unselected)
        _binding.orderIcon.setImageResource(R.mipmap.order_unselected)
        _binding.mineIcon.setImageResource(R.mipmap.mine_unselected)
        _binding.homePoint.invisible()
        _binding.orderPoint.invisible()
        _binding.minePoint.invisible()

        when (selectedIndex) {
            0 -> {
                _binding.homeIcon.setImageResource(R.mipmap.home_selected)
                _binding.homePoint.visible()
            }

            1 -> {
                if (_binding.orderBarContainer.isVisible) {
                    _binding.orderIcon.setImageResource(R.mipmap.order_selected)
                    _binding.orderPoint.visible()

                } else {
                    _binding.mineIcon.setImageResource(R.mipmap.mine_selected)
                    _binding.minePoint.visible()
                }
            }
            2 -> {
                _binding.mineIcon.setImageResource(R.mipmap.mine_selected)
                _binding.minePoint.visible()
            }
        }


    }

    private fun selectPage(selectedIndex: Int) {
        this.selectedIndex = selectedIndex
        _binding.viewPager.setCurrentItem(selectedIndex, true)
    }

    private fun initAdapter() {

        _binding.viewPager.adapter = object : FragmentStateAdapter(this) {
            override fun getItemId(position: Int): Long {
                return fragments[position].hashCode().toLong()
            }
            override fun getItemCount(): Int {
                return fragments.size
            }

            override fun createFragment(position: Int): Fragment {
                return fragments[position]
            }

            override fun containsItem(itemId: Long): Boolean {
                for (fragment in fragments) {
                    if (fragment.hashCode().toLong() == itemId) {
                        return true
                    }
                }
                return false
            }
        }
        _binding.viewPager.offscreenPageLimit = 3
        _binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                LogUtils.d("registerOnPageChangeCallback, $position")
                selectedIndex = position
                switchBottom()
            }
        })

    }

    private fun initArgs(savedInstanceState: Bundle?) {
        intent?.run {
            fromType = getIntExtra(FROM_TYPE, 0)
            injures = getParcelableArrayExtra(PageArgs.INJUREPACIFICCHICKENRES_DATAS) as? Array<InjurePacificChickenRes>
            LogUtils.d("homeactivity initargs $fromType, $injures")

        }

    }

    override fun isSetStatusbar(): Boolean {
        return true
    }

    companion object {
        private val TAG = "HomeActivity"
        fun jump(context: Context, fromType: Int, datas: List<InjurePacificChickenRes>? = null) {
            context.startActivity(
                Intent(context, HomeActivity::class.java)
                    .apply {
                        putExtra(FROM_TYPE, fromType)
                        datas?.let {
                            putExtra(PageArgs.INJUREPACIFICCHICKENRES_DATAS, it.toTypedArray())
                        }
                    }
            )
        }
    }

}